package com.jy.api.controller.member;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.jy.api.dao.MemberDao;
import com.jy.api.dao.OrderDao;
import com.jy.api.dao.StoreDao;
import com.jy.api.domain.Member;
import com.jy.api.domain.MemberAccount;
import com.jy.api.domain.Order;
import com.jy.api.domain.Store;
import com.jy.api.service.OrderService;
import com.jy.api.util.RedisSyncLocker;
import com.jy.api.util.WxMAConfiguration;
import com.jy.api.vo.pos.order.OrderVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by lihu on 2017/11/20.
 */
@Slf4j
@RestController
@RequestMapping(value = "/v1/member", produces = "application/json;charset=utf-8")
public class MemberOrderController {

    @Autowired
    MemberDao memberDao;

    @Autowired
    OrderService orderService;

    @Autowired
    OrderDao orderDao;

    @Autowired
    StoreDao storeDao;
    @Autowired
    private RedisSyncLocker redisSyncLocker;

    /**
     * 获取会员消费记录
     *
     * @param openid
     * @param pageable
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{openid}/orders")
    public ResponseEntity getMemberRecord(@PathVariable String openid,
                                          @PageableDefault(value = 10, sort = {"paymentTime"}, direction = Sort.Direction.DESC) Pageable pageable) {
        try {
            Member member = memberDao.findByOpenId(openid);
            if (member == null) {
                return new ResponseEntity("你不是店铺会员！请先成为会员！", HttpStatus.BAD_REQUEST);
            }

            return ResponseEntity.ok(orderService.getMemberRecord(member.getId(), pageable));

        } catch (Exception ex) {
            log.error("getMemberRecord is error==> openid:{},", openid, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    /**
     * 获取会员消费记录
     *
     * @param
     * @param pageable
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/get/store")
    public ResponseEntity getStore(@RequestParam("memberId") String memberId,
                                   @PageableDefault(value = 10, sort = {"paymentTime"}, direction = Sort.Direction.DESC) Pageable pageable) {
        try {
            Member member = memberDao.findOne(memberId);
            if (member == null) {
                return new ResponseEntity("你不是店铺会员！请先成为会员！", HttpStatus.BAD_REQUEST);
            }
            List<Store> stores = new ArrayList<>();
            Set<MemberAccount> memberSet = member.getAccounts();
            for (MemberAccount memberAccount : memberSet) {
                stores.add(storeDao.findOne(memberAccount.getStoreId()));
            }


            return ResponseEntity.ok(stores);

        } catch (Exception ex) {
            log.error("getMemberRecord is error==> openid:{},", memberId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    /**
     * 获取会员消费记录
     *
     * @param
     * @param pageable
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/orders")
    public ResponseEntity getMemberRecordByMemberId(@RequestParam("memberId") String memberId,@RequestParam("storeId") String storeId,
                                                    @PageableDefault(value = 10, sort = {"paymentTime"}, direction = Sort.Direction.DESC) Pageable pageable) {
        try {
            Member member = memberDao.findOne(memberId);
            if (member == null) {
                return new ResponseEntity("你不是店铺会员！请先成为会员！", HttpStatus.BAD_REQUEST);
            }
            return ResponseEntity.ok(orderService.getMemberRecordAndStoreId(member.getId(), storeId,pageable));

        } catch (Exception ex) {
            log.error("getMemberRecord is error==> openid:{},", memberId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @ApiOperation("小程序授权登录")
    @PostMapping("/waLogin")
    public ResponseEntity waLogin(@Valid @RequestBody WaLoginParams params, HttpServletRequest request) throws Exception {
        try {
            log.info(" login params :{}", params);
            final int platform = params.getType() - 1;
            final WxMaService maService = WxMAConfiguration.getMaService(platform);
            log.info(" maService config :{}", maService.getWxMaConfig());
            final WxMaJscode2SessionResult wxMaJscode2SessionResult = maService.jsCode2SessionInfo(params.getJsCode());
            log.info(" WxMaJscode2SessionResult :{}", wxMaJscode2SessionResult);
            final String openId = wxMaJscode2SessionResult.getOpenid();
            final String unionid = wxMaJscode2SessionResult.getUnionid();
            WxMaUserService userService = maService.getUserService();
            WxMaUserInfo userInfo = null;
            WxMaPhoneNumberInfo phoneNoInfo = null;
            userInfo = userService.getUserInfo(wxMaJscode2SessionResult.getSessionKey(), params.getEncryptedData(), params.getIv());
            phoneNoInfo = userService.getPhoneNoInfo(wxMaJscode2SessionResult.getSessionKey(), params.getEncryptedData(), params.getIv());
            if (null == phoneNoInfo) return ResponseEntity.badRequest().body("登录失败，请重试");
            if (StringUtils.isBlank(phoneNoInfo.getPhoneNumber())) {
                return ResponseEntity.badRequest().body("登录失败，请重试");
            }
            if (null == userInfo) return ResponseEntity.badRequest().body("登录失败，请重试");
            log.info(" WxMaJscode2SessionResult userInfo :{}", userInfo);
            log.info("微信返回用户信息{}", userInfo);
            System.out.println("微信返回结果" + phoneNoInfo);
            System.out.println("微信手机号" + phoneNoInfo.getPhoneNumber());
            Member member = memberDao.findTop1ByMobileOrderByUpdateTimeDesc(phoneNoInfo.getPhoneNumber());
            if (member!=null){
                return ResponseEntity.ok(member);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("用户登陆异常{}",e);
        }
        return ResponseEntity.badRequest().body("会员号码不存在，请联系门店员工添加会员方可继续操作");
    }


    /**
     * 订单明细
     *
     * @param orderId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "{orderId}/order-info")
    public ResponseEntity getOrderInfo(@PathVariable String orderId) {
        try {
            return (ResponseEntity) redisSyncLocker.idLock(orderId, o -> {
                Order order = orderDao.findOne(orderId);
                if (order == null) {
                    return new ResponseEntity("查询失败！订单信息不存在！", HttpStatus.BAD_REQUEST);
                }
                Store store = storeDao.findOne(order.getStoreId());
                OrderVo orderVo = orderService.orderVoCouponInstance(order);
                orderVo.setStoreName(store.getName());
                orderVo.setStoreAddress(store.getAddr());
                return ResponseEntity.ok(orderVo);
            });
        } catch (Exception ex) {

            log.error("getChargeRules is error=>orderId:{}", orderId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

}

